<!DOCTYPE HTML>
<html lang="en">

<head>
    <!--Setting-->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta http-equiv="Cache-Control" content="no-transform">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta name="apple-mobile-web-app-capable" content="Sanphone&#39;Blog">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    <meta name="browsermode" content="application">
    <meta name="screen-orientation" content="portrait">
    <meta name="theme-version" content="1.3.0">
    <meta name="root" content="/blog/">
    <link rel="dns-prefetch" href="https://wuxiangfeng.gitee.io/sanphone.gitee.io">
    <!--SEO-->

<meta name="keywords" content="c++" />


<meta name="description" content="前言C++的学习中，我想每个人都被变量定义和申明折磨过，比如我在大学笔试过的几家公司，都考察了const和变量，类型的不同排列组合，让你区别有啥不同。反正在学习C++过程中已经被折磨惯了，今天再..." />


<meta name="robots" content="all" />
<meta name="google" content="all" />
<meta name="googlebot" content="all" />
<meta name="verify" content="all" />
    <!--Title-->

<title>
    
    c++11之初始化列表 |
    
    Sanphone&#39;Blog
</title>

<link rel="alternate" href="/atom.xml" title="Sanphone&#39;Blog" type="application/atom+xml">


<link rel="icon" href="/favicon.ico">

    


<link rel="stylesheet" href="/blog/css/bootstrap.min.css?rev=3.3.7.css">
<link rel="stylesheet" href="/blog/css/font-awesome.min.css?rev=4.7.0.css">
<link rel="stylesheet" href="/blog/css/style.css?rev=@@hash.css">

    
<div class="hide">
    <script type="text/javascript">
    var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");
    document.write(unescape("%3Cspan class='cnzz_stat_icon_1263868967 hide' %3E%3Cscript%20src%3D%22https%3A%2F%2Fs95.cnzz.com%2Fz_stat.php%3Fweb_id%3D1272564536%22%3E%3C%2Fscript%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s19.cnzz.com/z_stat.php%3Fid%3D1263868967%26show%3Dpic1' type='text/javascript'%3E%3C/script%3E"));
    </script>
</div>




    

<meta name="generator" content="Hexo 6.3.0"></head>
<!--[if lte IE 8]>
<style>
    html{ font-size: 1em }
</style>
<![endif]-->
<!--[if lte IE 9]>
<div style="ie">你使用的浏览器版本过低，为了你更好的阅读体验，请更新浏览器的版本或者使用其他现代浏览器，比如Chrome、Firefox、Safari等。</div>
<![endif]-->
<body>
    <header class="main-header"  style="background-image:url(
    https://hexo-theme-snippet-1251680922.cos.ap-beijing.myqcloud.com/img/banner.jpg)"
     >
    <div class="main-header-box">
        <a class="header-avatar" href="/" title='Sanphone'>
            <img src="/blog/img/avatar.jpg" alt="logo头像" class="img-responsive center-block">
        </a>
        <div class="branding">
            <!--<h2 class="text-hide">Snippet主题,从未如此简单有趣</h2>-->
            
            <img src="/blog/img/branding.png" alt="Snippet 博客主题" class="img-responsive center-block">
            
        </div>
    </div>
</header>
    <nav class="main-navigation">
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <div class="navbar-header"><span class="nav-toggle-button collapsed pull-right" data-toggle="collapse" data-target="#main-menu" id="mnav">
                        <span class="sr-only"></span>
                        <i class="fa fa-bars"></i>
                    </span>
                    <a class="navbar-brand" href="https://wuxiangfeng.gitee.io/sanphone.gitee.io">
                        Sanphone&#39;Blog</a>
                </div>
                <div class="collapse navbar-collapse" id="main-menu">
                    <ul class="menu">
                        
                        <li role="presentation" class="text-center">
                            <a href="/bolg"><i class="fa "></i>
                                主页</a>
                        </li>
                        
                        <li role="presentation" class="text-center">
                            <a href="/bolg/categories/前端/"><i class="fa "></i>
                                前端</a>
                        </li>
                        
                        <li role="presentation" class="text-center">
                            <a href="/bolg/categories/后端/"><i class="fa "></i>
                                后端</a>
                        </li>
                        
                        <li role="presentation" class="text-center">
                            <a href="/bolg/categories/移动端/"><i class="fa "></i>
                                移动端</a>
                        </li>
                        
                        <li role="presentation" class="text-center">
                            <a href="/bolg/categories/中间件/"><i class="fa "></i>
                                中间件</a>
                        </li>
                        
                        <li role="presentation" class="text-center">
                            <a href="/bolg/categories/工具/"><i class="fa "></i>
                                工具</a>
                        </li>
                        
                        <li role="presentation" class="text-center">
                            <a href="/bolg/archives/"><i class="fa "></i>
                                时间轴</a>
                        </li>
                        
                    </ul>
                </div>
            </div>
        </div>
    </div>
</nav>
    <section class="content-wrap">
        <div class="container">
            <div class="row">
                <main class="col-md-8 main-content m-post">
                    <p id="process"></p>
<article class="post">
    <div class="post-head">
        <h1 id="c++11之初始化列表">
            
            c++11之初始化列表
            
        </h1>
        <div class="post-meta">
    
    <span class="categories-meta fa-wrap">
        <i class="fa fa-folder-open-o"></i>
        <a class="category-link" href="/blog/categories/%E5%90%8E%E7%AB%AF/">后端</a> <a class="category-link" href="/blog/categories/%E5%90%8E%E7%AB%AF/c/">c++</a>
    </span>
    
    
    <span class="fa-wrap">
        <i class="fa fa-tags"></i>
        <span class="tags-meta">
            
            <a class="tag-none-link" href="/blog/tags/c/" rel="tag">c++</a>
            
        </span>
    </span>
    
    
    
    <span class="fa-wrap">
        <i class="fa fa-clock-o"></i>
        <span class="date-meta">
            2024/02/02</span>
    </span>
    
    <span class="fa-wrap">
        <i class="fa fa-eye"></i>
        <span id="busuanzi_value_page_pv"></span>
    </span>
    
    
</div>
        
        
    </div>
    
    <div class="post-body post-content">
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>C++的学习中，我想每个人都被变量定义和申明折磨过，比如我在大学笔试过的几家公司，都考察了const和变量，类型的不同排列组合，让你区别有啥不同。反正在学习C++过程中已经被折磨惯了，今天再来看看重温下那段“辉煌的历史”。先来看一段代码：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Player pa                               // (a)</span><br><span class="line">Player pb();                            // (b)</span><br><span class="line">Player pc = Player();                   // (c)    </span><br><span class="line">Player pd(Player());                    // (d)      </span><br><span class="line">pd = Player()                           // (e)</span><br></pre></td></tr></table></figure>
<p>a，c，d 都是申明一个变量，a 很容易理解就是申明一个变量，b第一感觉是调用构造函数来申明变量，其实不是，而是申明一个无参数，返回Player的函数。对于c以为是调用了operator&#x3D; 赋值运算吧？完全不是，而是先生成一个对象，然后调用Player的拷贝构造函数，生成对象pc。d和c是一样的。e才是真正调用赋值操作。是不是已经被这各式各样的对象申明搞的晕头专向了。现在C++11初始化列表正式登场。</p>
<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>在看C++11初始化前，先来回忆一下C语言中的结构体初始化，代码如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;iostream&gt;  </span><br><span class="line">  </span><br><span class="line">struct Player&#123;  </span><br><span class="line">    int id;  </span><br><span class="line">    const char* name;  </span><br><span class="line">&#125;;  </span><br><span class="line">  </span><br><span class="line">int main() &#123;  </span><br><span class="line">    Player player = &#123;10001, &quot;c++&quot;&#125;;  </span><br><span class="line">    printf(&quot;%d, %s\n&quot;, player.id, player.name);  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<p>结构体变量可以列表初始化，非常方便。C++11引入了初始化列表来初始化变量和对象。</p>
<h2 id="如何使用"><a href="#如何使用" class="headerlink" title="如何使用"></a>如何使用</h2><ol>
<li>系统内置类型<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">int ia&#123;1&#125;;                // (a)  </span><br><span class="line">int ib = &#123;1&#125;;             // (b)     </span><br><span class="line">int ic(1);                // (c)   </span><br><span class="line">int id = 1;               // (d) </span><br></pre></td></tr></table></figure>
很明显，还是d 更符合习惯。<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">std::vector&lt;int&gt; va&#123;1, 2, 3&#125;;          // (a)  </span><br><span class="line">std::vector&lt;int&gt; vb = &#123;1, 2, 3&#125;;       // (b)      </span><br><span class="line">std::vector&lt;int&gt; vc(1, 10);            // (c)     </span><br><span class="line">std::vector&lt;int&gt; vd&#123;1, 10&#125;;            // (d)</span><br></pre></td></tr></table></figure>
通过初始化列表可以弥补c中只能初始化相同数字的问题。在使用中c和d不要混淆了。<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">std::pair&lt;int, const char*&gt; getPlayer() &#123;  </span><br><span class="line">     return &#123;10001, &quot;c++&quot;&#125;;  </span><br><span class="line"> &#125;  </span><br><span class="line">std::map&lt;int, const char*&gt; players = &#123;&#123;10001, &quot;c++&quot;&#125;, &#123;10002, &quot;java”&#125;&#125;; </span><br></pre></td></tr></table></figure>
还可以返回pair类型，初始化map都是可以的。</li>
<li>自定义类型<br>对于单个参数初始化，类型匹配构造函数，不需要自定义构造函数。<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Player pa&#123;&#125;;                    // (a)  </span><br><span class="line">Player pb;                      // (b)    </span><br><span class="line">Player pc();                    // (c)  </span><br><span class="line">Player pd(b);                   // (d)  </span><br><span class="line">Player pe = b;                  // (e)  </span><br><span class="line">Player pf = &#123;b&#125;;                // (f) </span><br></pre></td></tr></table></figure>
对于上面几种变量初始化，推荐a, 如果是带参数的构造函数，推荐b，若果是不带参数的构造函数。</li>
<li>如果是自己想实现初始化列表构造函数，拷贝函数，赋值函数，需要包含initializer_list 这个头文件。<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">class MyClass&#123;  </span><br><span class="line">public:  </span><br><span class="line">    MyClass(int a):a_(a)&#123;  </span><br><span class="line">        std::cout &lt;&lt; &quot;normal initializer list\n&quot;;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    MyClass(std::initializer_list&lt;int&gt; a):b_(a) &#123;  </span><br><span class="line">        std::cout &lt;&lt; &quot;initializer list constructor\n&quot;;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    MyClass(MyClass&amp; my) &#123;  </span><br><span class="line">        std::cout &lt;&lt; &quot;copy constructor\n&quot;;  </span><br><span class="line">        this-&gt;a_ = my.a_;  </span><br><span class="line">        this-&gt;b_ = my.b_;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    MyClass&amp; operator=(MyClass&amp; my) &#123;  </span><br><span class="line">        std::cout &lt;&lt; &quot;operator = constructor\n&quot;;  </span><br><span class="line">        this-&gt;a_ = my.a_;  </span><br><span class="line">        this-&gt;b_ = my.b_;  </span><br><span class="line">        return *this;  </span><br><span class="line">    &#125;  </span><br><span class="line">private:  </span><br><span class="line">    int a_;  </span><br><span class="line">    std::initializer_list&lt;int&gt; b_;  </span><br><span class="line">&#125;; </span><br></pre></td></tr></table></figure>
这是自定义类，带有初始化列表构造函数的类，下面来练习下学过的类相关C++知识：<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">MyClass ma&#123;1&#125;;               // (a)  </span><br><span class="line">MyClass mb = &#123;1, 2, 3&#125;;      // (b)  </span><br><span class="line">MyClass mc(2);               // (c)  </span><br><span class="line">MyClass md = b;              // (d)  </span><br><span class="line">MyClass me(c);               // (e)  </span><br><span class="line">MyClass mf&#123;e&#125;;               // (f)  </span><br><span class="line">auto l&#123;2, 2, 3,3&#125;;  </span><br><span class="line">MyClass mh&#123;l&#125;;               // (e)  </span><br><span class="line">ma = mb;                     // (h)</span><br></pre></td></tr></table></figure>
看一下每次调用都输出什么结果，答案在这里：<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">nitializer list constructor</span><br><span class="line">initializer list constructor</span><br><span class="line">normal constructor list</span><br><span class="line">copy constructor</span><br><span class="line">copy constructor</span><br><span class="line">copy constructor</span><br><span class="line">initializer list constructor</span><br><span class="line">operator = constructor</span><br></pre></td></tr></table></figure></li>
</ol>
<h2 id="为啥需要初始化列表"><a href="#为啥需要初始化列表" class="headerlink" title="为啥需要初始化列表"></a>为啥需要初始化列表</h2><ol>
<li>避免类申明对象混淆，区分对待，对于C++为啥有小括号初始化对象这一说，大家可以自行google，看来不管是谁都有犯错误的时候，勇于承认错误还是好同志。</li>
<li>在初始化多个变量时方便</li>
<li>避免数据切割，因为通过初始化列表是不允许隐式转换的。</li>
</ol>
<h2 id="注意事项"><a href="#注意事项" class="headerlink" title="注意事项"></a>注意事项</h2><ol>
<li>在申明变量的时候，少用小括号，程序可读性更高</li>
<li>使用初始化列表防止隐式转换，减少bug</li>
<li>通过 {} 返回的对象是const类型，不可转换</li>
</ol>

    </div>
    
    <div class="post-footer">
        <div>
            
            转载声明：
            商业转载请联系作者获得授权,非商业转载请注明出处 © <a href="" target="_blank">Snippet</a>
            
            
        </div>
        <div>
            
        </div>
    </div>
</article>
<div class="article-nav prev-next-wrap clearfix">
    
    <a href="/blog/2024/02/02/%E5%9E%83%E5%9C%BE%E6%94%B6%E9%9B%86%E5%99%A8/" class="pre-post btn btn-default" title='垃圾收集器'>
        <i class="fa fa-angle-left fa-fw"></i><span class="hidden-lg">上一篇</span>
        <span class="hidden-xs">
            垃圾收集器</span>
    </a>
    
    
    <a href="/blog/2024/02/01/ES-%E8%BD%BB%E9%87%8F%E6%9F%A5%E8%AF%A2-%E5%9F%BA%E4%BA%8EES5-6%E7%89%88%E6%9C%AC/" class="next-post btn btn-default" title='ES-轻量查询---基于ES5.6版本'>
        <span class="hidden-lg">下一篇</span>
        <span class="hidden-xs">
            ES-轻量查询---基于ES5.6版本</span><i class="fa fa-angle-right fa-fw"></i>
    </a>
    
</div>

<div id="comments">
    
    
<div class="utteranc">
  
  <script
    src='https://utteranc.es/client.js'
    repo='shenliyang/snippet-comment'
    issue-term='pathname'
    issue-number=''
    theme='github-light'
    label=''
    crossorigin='anonymous'
    async
  ></script>
</div>



</div>

                </main>
                
                    <aside id="article-toc" role="navigation" class="col-md-4">
    <div class="widget">
        <h3 class="title">
            Table of Contents
        </h3>
        
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AE%80%E4%BB%8B"><span class="toc-text">简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8"><span class="toc-text">如何使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%BA%E5%95%A5%E9%9C%80%E8%A6%81%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8"><span class="toc-text">为啥需要初始化列表</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9"><span class="toc-text">注意事项</span></a></li></ol>
        
    </div>
</aside>
                
            </div>
        </div>
    </section>
    <footer class="main-footer">
    <div class="container">
        <div class="row">
        </div>
    </div>
</footer>
<a id="back-to-top" class="icon-btn hide">
    <i class="fa fa-chevron-up"></i>
</a>
    <div class="copyright">
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <div class="busuanzi">
    
    Total:
    <strong id="busuanzi_value_site_pv">
        <i class="fa fa-spinner fa-spin"></i>
    </strong>
    &nbsp; | &nbsp;
    Visitors:
    <strong id="busuanzi_value_site_uv">
        <i class="fa fa-spinner fa-spin"></i>
    </strong>
    
</div>
            </div>
            <div class="col-sm-12">
                <span>Copyright &copy;
                    2017
                    
                </span> |
                <span>
                    Powered by <a href="//hexo.io" class="copyright-links" target="_blank" rel="nofollow">Hexo</a>
                </span> |
                <span>
                    Theme by <a href="//github.com/shenliyang/hexo-theme-snippet.git" class="copyright-links" target="_blank" rel="nofollow">Snippet</a>
                </span>
            </div>
        </div>
    </div>
</div>



<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>


<script src="/blog/js/app.js?rev=@@hash.js"></script>

</body>
</html>